package com.uchedao.mybaselibrary.activity;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.baidu.mobstat.StatService;
import com.uchedao.mybaselibrary.http.VolleyUtil;
import com.uchedao.mybaselibrary.utils.NetUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * Fragment 基础类
 * Created by zhengxizhen on 15/8/11.
 */
public abstract class BaseFragment extends Fragment {
    /**
     * 当前布局视图
     */
    protected View mRoot;

    /**
     * 当前软件Context
     */
    protected Context mContext;

    /**
     * 页面标签
     */
    protected String TAG = "BaseFragment";
    /**
     *
     * */
    protected RequestQueue mQueue;

    /**
     * 设置页面标签
     */
    protected abstract String getActivityTag();

    /**
     * 获取布局XML ID
     */
    protected abstract int getLayoutResID();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 初始化监听事件
     */
    protected abstract void initListener();

    public BaseFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        //获取单例网络请求队列
        mQueue = VolleyUtil.getInstance(getActivity()).getRequestQueue(getActivity());
        TAG = getActivityTag();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRoot = inflater.inflate(getLayoutResID(), container, false);
        initView();
        initView();
        initData();
        initListener();
        return mRoot;
    }

    protected View findViewById(int id) {
        return mRoot.findViewById(id);
    }

    @Override
    public void onStop() {
        //取消请求
        if(!TextUtils.isEmpty(TAG)) {
            mQueue.cancelAll(TAG);
        }
        super.onStop();
    }

    public void showToast(String msg){
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 添加网络请求
     */
    public void addQueue(Request request) {
        if(!TextUtils.isEmpty(TAG)) {
            if (NetUtil.isNet(getActivity()) && request != null) {
                request.setTag(TAG);
                mQueue.add(request);
            } else {
                mQueue.cancelAll(TAG);
            }
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(mContext);
        StatService.onPageStart(mContext, TAG);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(mContext);
        StatService.onPageEnd(mContext, TAG);
    }
}
